//
//  UserAccount.m
//  OCMicroBlog
//
//  Created by 002 on 15/11/5.
//  Copyright © 2015年 002. All rights reserved.
//

#import "UserAccount.h"

@interface UserAccount ()<NSCoding>

@end

@implementation UserAccount

/**
 *  保存当前用户信息到沙盒
 */
- (void)saveUserAccount {
    
    NSString *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, true)[0];
    
    path = [path stringByAppendingPathComponent:@"account.plist"];
    
    NSLog(@"%@",path);
    
    [NSKeyedArchiver archiveRootObject:self toFile:path];
}

+ (instancetype)initWithDict:(NSDictionary *)dict {

    UserAccount *userAccount = [[UserAccount alloc] init];
    
    [userAccount setValuesForKeysWithDictionary:dict];
    
    return userAccount;
}

- (void)setValue:(id)value forUndefinedKey:(NSString *)key {};

/**
 *  模型调试信息
 *
 *  @return
 */
- (NSString *)description {
    
    NSArray *keys = @[@"access_token", @"expires_in", @"expiresDate", @"uid", @"screen_name", @"avatar_large"];
    
    return [self dictionaryWithValuesForKeys:keys].description;
}

/**
 *  设置过期日期
 *
 *  @param expires_in 过期时间 单位 秒
 */
- (void)setExpires_in:(NSTimeInterval)expires_in {
    _expires_in = expires_in;
    _expiresDate = [[NSDate alloc] initWithTimeIntervalSinceNow:expires_in];
}

#pragma mark - NSCoding
/**
 *  归档 -> 将当前归档保存至二进制之前被调用
 *
 *  @param aCoder 编码器
 */
- (void)encodeWithCoder:(NSCoder *)aCoder {

    [aCoder encodeObject:_access_token forKey:@"_access_token"];
    [aCoder encodeObject:_expiresDate forKey:@"_expiresDate"];
    [aCoder encodeObject:_uid forKey:@"_uid"];
    [aCoder encodeObject:_screen_name forKey:@"_screen_name"];
    [aCoder encodeObject:_avatar_large forKey:@"_avatar_large"];
}

/**
 *  解档 -> 从二进制文件恢复成对象时调用，与网络的反序列化功能类似
 *
 *  @param aDecoder 解码器
 *
 *  @return 用户账户对象
 */
- (instancetype)initWithCoder:(NSCoder *)aDecoder {
    
    _access_token = [aDecoder decodeObjectForKey:@"_access_token"];
    _expiresDate = [aDecoder decodeObjectForKey:@"_expiresDate"];
    _uid = [aDecoder decodeObjectForKey:@"_uid"];
    _screen_name = [aDecoder decodeObjectForKey:@"_screen_name"];
    _avatar_large = [aDecoder decodeObjectForKey:@"_avatar_large"];
    
    return self;
}

@end
